<template>
  <a-drawer
    :title="title"
    :width="720"
    :visible="visible"
    :wrapStyle="{height: '100%',overflow: 'auto',paddingBottom: '108px'}"
    @close="close"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="标题"
        >
          <a-input placeholder="请输入案例标题" v-decorator="[ 'title', {rules: [{ required: true, message: '请输入案例标题!' }]}]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="描述"
        >
          <a-input placeholder="请输入案例描述" v-decorator="[ 'description', {rules: [{ required: false, message: '请输入案例描述!' }]}]"/>
        </a-form-item>

        <a-form-item label="封面" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            v-decorator="[
              'fileField',
              {
                valuePropName: 'fileList',
                getValueFromEvent: normFile,
                initialValue: [],
                preserve: true,
                rules: [{ required: true, message: '请选择封面图片!' }]
              },
            ]"
            listType="picture-card"
            :beforeUpload="handleBeforeUploadPhoto"
            :customRequest="uploadPhoto"
            :remove="removePhoto"
            @preview="handlePreviewPhoto"
          >
            <div v-if="showUpload">
              <a-icon type="plus" />
              <div class="ant-upload-text">点击上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item hidden>
          <a-input v-decorator="[ 'coverFileId' ]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="视频详情"
        >
          <a-input placeholder="请输入视频详情" v-decorator="[ 'detail', {rules: [{ required: false, message: '请输入视频详情!' }]}]"/>
        </a-form-item>

        <a-form-item label="视频" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            v-decorator="[
              'videoFileField',
              {
                valuePropName: 'fileList',
                getValueFromEvent: normFile,
                initialValue: [],
                preserve: true,
                rules: [{ required: true, message: '请上传视频文件!' }]
              },
            ]"
            :beforeUpload="handleBeforeUploadVideo"
            :customRequest="uploadVideo"
            :remove="removeVideo"
          >
            <a-button v-if="showUploadVideo"> <a-icon type="upload" /> 点击上传 </a-button>
          </a-upload>
          <vue-d-player v-show="showPlayer" ref="dPlayer" id="dPlayer" :options="options"></vue-d-player>
        </a-form-item>
        <a-form-item hidden>
          <a-input v-decorator="[ 'videoFileId' ]"/>
        </a-form-item>

      </a-form>
    </a-spin>

    <div style="padding: 20px 40px 60px 40px" v-if="showComment">
      <comment :caseInfoId="model.id"></comment>
    </div>

    <a-modal width="100%" :visible="previewVisible" :footer="null" @cancel="previewVisible = false" centered>
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>

    <div class="drawer-bottom-button" v-if="!showComment">
      <a-button :style="{marginRight: '8px'}" @click="close">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { TreeSelect } from 'ant-design-vue'
import { FormModalMixin } from '@/mixins/FormModalMixin'
import { apiQueryCaseInfoById, apiSaveCaseInfo, apiUpdateCaseInfo } from '@/api/article'
import pick from 'lodash.pick'
import { apiUploadFile, apiUploadFileBase64 } from '@/api/file'
import { CASE_INFO_STATUS_ENUM } from '@/store/mutation-types'
import VueDPlayer from 'vue-dplayer'
import 'vue-dplayer/dist/vue-dplayer.css'
import Comment from './Comment'
import lrz from 'lrz'

const options = {
    container: document.getElementById('dPlayer'), // 播放器容器
    mutex: false, //  防止同时播放多个用户，在该用户开始播放时暂停其他用户
    theme: '#b7daff', // 风格颜色，例如播放条，音量条的颜色
    loop: false, // 是否自动循环
    lang: 'zh-cn', // 语言，'en', 'zh-cn', 'zh-tw'
    screenshot: true, // 是否允许截图（按钮），点击可以自动将截图下载到本地
    hotkey: true, // 是否支持热键，调节音量，播放，暂停等
    preload: 'auto', // 自动预加载
    video: {
      url: ''
    },
    contextmenu: [{
      text: '删除当前视频',
      click: (player) => { console.log(player) }
    }]
}

export default {
  name: 'CaseInfoModal',
  components: {
    TreeSelect, VueDPlayer, Comment
  },
  mixins: [FormModalMixin],
  data () {
    return {
      options,
      previewVisible: false,
      previewImage: '',
      showUpload: true,
      showUploadVideo: true,
      showPlayer: false,
      uploadVideo: null,
      showComment: false,
      caseInfoStatusEnum: CASE_INFO_STATUS_ENUM
    }
  },
  created () {
    this.uploadVideo = (option) => {
      const formData = new FormData()
      formData.append('multipartFile', option.file)
      this.showUploadVideo = false
      apiUploadFile(formData, (e) => {
        console.log('apiUploadFile=', e)
        let percent = (e.loaded / e.total) * 100
        if (percent > 99) {
          percent = 99
        }
        option.onProgress({ percent: percent })
      }).then(res => {
        option.onProgress({ percent: 100 })
        console.log('onSuccess')
        this.form.setFieldsValue({
          videoFileId: res.data.id
        })
        option.onSuccess()
        this.showPlayer = true
        // 切换视频
        this.$refs.dPlayer.dp.switchVideo({
          url: res.data.url
        })
      }).catch(err => {
        option.onError(err, err.message)
      })
    }
  },
  methods: {
    show (title, record) {
      this.resetFields()
      this.model = {}
      this.showUpload = true
      this.showUploadVideo = true
      this.showPlayer = false
      this.visible = true
      this.title = title
      if (record) {
        this.showComment = record.showComment
        apiQueryCaseInfoById(record.id).then(res => {
          this.model = Object.assign({}, res.data)
          this.model.id = record.id
          this.$nextTick(() => {
            this.showUpload = false
            this.form.setFieldsValue(pick(this.model, 'title', 'description', 'coverFileId', 'videoFileId', 'detail'))
            this.form.setFieldsValue({
              fileField: [{
                uid: this.model.coverFileId,
                status: 'done',
                url: this.model.coverFileUrl,
                name: '封面'
              }],
              videoFileField: [{
                uid: this.model.videoFileId,
                status: 'done',
                url: this.model.videoFileUrl,
                name: '视频'
              }]
            })
            this.showPlayer = true
            this.showUploadVideo = false
            // 切换视频
            this.$refs.dPlayer.dp.switchVideo({
              url: this.model.videoFileUrl
            })
          })
        })
      }
    },
    normFile (e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    handleBeforeUploadPhoto (file, fileList) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      return new Promise((resolve, reject) => {
        if (!isJPG) {
          this.$message.error('请选择jpg或png文件！')
          reject(file)
        } else if (fileList.length > 1) {
          this.$message.error('最多上传1个文件！')
        } else {
          resolve(file)
        }
      })
    },
    uploadPhoto (e) {
      this.showUpload = false
      const formData = new FormData()
      formData.append('multipartFile', e.file)
      lrz(e.file, { quality: 0.7 }).then(rst => {
        apiUploadFileBase64(rst.base64, (progress) => {
          console.log('apiUploadFile=', progress)
          let percent = (progress.loaded / progress.total) * 100
          if (percent > 99) {
            percent = 99
          }
          e.onProgress({ percent: percent })
        }).then(res => {
          console.log('uploadPhoto=>', res)
          this.form.setFieldsValue({
            coverFileId: res.data.id
          })
          e.onSuccess()
        }).catch(err => {
          e.onError(err, err.message)
        })
      })
    },
    removePhoto () {
      this.showUpload = true
      this.form.setFieldsValue({
        fileField: [],
        coverFileId: null
      })
    },
    handlePreviewPhoto (file) {
      console.log(file)
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleBeforeUploadVideo (file, fileList) {
      console.log('上传的文件==>', file)
      const videoTypes = ['video/mp4', 'video/x-ms-asf', 'video/avi', 'video/x-ivf', 'video/x-mpeg', 'video/mpeg4', 'video/x-sgi-movie', 'video/x-mpg', 'video/mpg', 'video/x-ms-wmv', 'video/x-ms-wm', 'video/x-ms-wmx', 'video/x-ms-wvx']
      const flag = videoTypes.indexOf(file.type) >= 0
      return new Promise((resolve, reject) => {
        if (!flag) {
          this.$message.error('不支持的视频文件！')
          reject(file)
        } else if (fileList.length > 1) {
          this.$message.error('最多上传1个文件！')
        } else {
          resolve(file)
        }
      })
    },
    removeVideo () {
      this.showUploadVideo = true
      this.showPlayer = false
      this.form.setFieldsValue({
        videoFileField: [],
        videoFileId: null
      })
    },
    removePalyer (player) {
      console.log(player)
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = false
          const formData = pick(Object.assign(this.model, values), 'title', 'description', 'coverFileId', 'videoFileId', 'detail', 'status')
          if (formData.description == null) {
            formData.description = ''
          }
          if (formData.detail == null) {
            formData.detail = ''
          }
          let obj
          if (this.model.id) {
            obj = apiUpdateCaseInfo(this.model.id, formData)
          } else {
            formData.status = this.caseInfoStatusEnum.INIT.KEY
            obj = apiSaveCaseInfo(formData)
          }
          obj.then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg)
              this.$emit('ok', res.data)
              this.close()
            } else {
              this.$message.warning(res.msg)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
